Param()

# run-cj-bench.ps1 - simplified and robust version
# Usage: set $env:CANGJIE_RUN_CMD to the command that starts the Cangjie server (e.g. 'cjpm run' or 'node cj-impl-shim.js')

$cjCmd = $env:CANGJIE_RUN_CMD
if ([string]::IsNullOrWhiteSpace($cjCmd)) {
    Write-Host 'CANGJIE_RUN_CMD 未设置。请先设置环境变量，例如:' -ForegroundColor Yellow
    Write-Host "    `$env:CANGJIE_RUN_CMD = 'cjpm run'"
    exit 1
}

Write-Host "Starting Cangjie server using command: $cjCmd"

$workDir = (Resolve-Path .).Path
$stdoutPath = Join-Path $workDir 'bench\cj_stdout.log'
$stderrPath = Join-Path $workDir 'bench\cj_stderr.log'

# Start the process via powershell -Command <cmd> to allow complex commands; pass ArgumentList as array to avoid quoting issues
try {
    $proc = Start-Process -FilePath 'powershell.exe' -ArgumentList '-NoProfile', '-Command', $cjCmd -WorkingDirectory $workDir -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath -PassThru
} catch {
    Write-Host '无法用 Start-Process 启动命令，错误：' $_ -ForegroundColor Red
    exit 3
}

if (-not $proc) { Write-Host '无法启动进程，Start-Process 返回空' -ForegroundColor Red; exit 3 }
Write-Host "Started process id: $($proc.Id)"

# wait for readiness
$url = 'http://localhost:3000/'
Write-Host "Waiting for $url to be ready..."
for ($i=0; $i -lt 60; $i++) {
    try {
        $r = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 1 -ErrorAction Stop
        if ($r.StatusCode -eq 200) { Write-Host 'Service ready'; break }
    } catch { Start-Sleep -Milliseconds 200 }
}

if ($i -ge 60) {
    Write-Host '服务未在超时时间内就绪，退出' -ForegroundColor Red
    Write-Host '最近 stdout (tail 50 lines):'
    try { Get-Content $stdoutPath -Tail 50 } catch {}
    Write-Host '最近 stderr (tail 50 lines):'
    try { Get-Content $stderrPath -Tail 50 } catch {}
    try { Stop-Process -Id $proc.Id -ErrorAction SilentlyContinue } catch {}
    exit 2
}

Write-Host 'Running built-in Node bench against /api/hello ...'
Write-Host 'Running bench: 50 connections for 10s against http://localhost:3000/api/hello'

$benchScript = Join-Path -Path $workDir -ChildPath 'node-ref\bench\simple-bench.js'
if (-not (Test-Path $benchScript)) { Write-Host "找不到 bench 脚本： $benchScript" -ForegroundColor Red; try { Stop-Process -Id $proc.Id -ErrorAction SilentlyContinue } catch {}; exit 4 }

node $benchScript -c 50 -d 10 http://localhost:3000/api/hello 2>&1 | Tee-Object -Variable benchOut

$timestamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
$outPath = Join-Path -Path $workDir -ChildPath "bench\results\cj-baseline-$timestamp.txt"
$benchOut | Out-File -FilePath $outPath -Encoding utf8
Write-Host "Saved CJ bench output to $outPath"

Write-Host "Stopping Cangjie server (pid: $($proc.Id))"
try { Stop-Process -Id $proc.Id -ErrorAction SilentlyContinue } catch {}

Write-Host 'Recent stdout (tail 80 lines):'
try { Get-Content $stdoutPath -Tail 80 } catch {}
Write-Host 'Recent stderr (tail 80 lines):'
try { Get-Content $stderrPath -Tail 80 } catch {}

Write-Host 'Done.'
